/**
 * 统一的API服务层
 * 负责所有与后端的通信
 */

const API_BASE_URL = 'http://localhost:3000/api'

class ApiService {
  constructor() {
    this.token = localStorage.getItem('auth_token')
  }

  /**
   * 通用请求方法
   */
  async request(url, options = {}) {
    const config = {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      ...options
    }

    // 添加认证token
    if (this.token) {
      config.headers.Authorization = `Bearer ${this.token}`
    }

    // 处理请求体 - 对于FormData，不要转换为JSON字符串
    if (config.body && typeof config.body === 'object' && !(config.body instanceof FormData)) {
      config.body = JSON.stringify(config.body)
    }

    // 如果是FormData请求，删除Content-Type头，让浏览器自动设置
    if (config.body instanceof FormData) {
      delete config.headers['Content-Type'];
    }

    try {
      const response = await fetch(`${API_BASE_URL}${url}`, config)
      
      // 检查响应状态
      if (!response.ok) {
        if (response.status === 401) {
          // Token过期，清除本地token
          this.clearAuth()
          throw new Error('认证失败，请重新登录')
        }
        const errorData = await response.json()
        throw new Error(errorData.message || `HTTP ${response.status}`)
      }

      return await response.json()
    } catch (error) {
      console.error('API请求失败:', error)
      throw error
    }
  }

  /**
   * GET请求
   */
  async get(url, params = {}) {
    const queryString = new URLSearchParams(params).toString()
    const fullUrl = queryString ? `${url}?${queryString}` : url
    return this.request(fullUrl, { method: 'GET' })
  }

  /**
   * POST请求
   */
  async post(url, data = {}) {
    return this.request(url, {
      method: 'POST',
      body: data
    })
  }

  /**
   * PUT请求
   */
  async put(url, data = {}) {
    return this.request(url, {
      method: 'PUT',
      body: data
    })
  }

  /**
   * DELETE请求
   */
  async delete(url) {
    return this.request(url, { method: 'DELETE' })
  }

  /**
   * 设置认证token
   */
  setToken(token) {
    this.token = token
    localStorage.setItem('auth_token', token)
  }

  /**
   * 清除认证信息
   */
  clearAuth() {
    this.token = null
    localStorage.removeItem('auth_token')
    localStorage.removeItem('currentUser')
  }

  // ==================== 用户认证API ====================

  /**
   * 用户登录
   */
  async login(email, password) {
    const response = await this.post('/auth/login', { email, password })
    // 后端返回的数据结构是 {success, message, data: {token, user}}
    if (response.data && response.data.token) {
      this.setToken(response.data.token)
      localStorage.setItem('currentUser', JSON.stringify(response.data.user))
      // 返回正确的用户对象，以便LoginModal可以正确访问
      return {
        ...response,
        user: response.data.user,
        token: response.data.token
      }
    }
    return response
  }

  /**
   * 用户注册
   */
  async register(userData) {
    const response = await this.post('/auth/register', userData)
    // 后端返回的数据结构是 {success, message, data: {token, user}}
    if (response.data && response.data.token) {
      this.setToken(response.data.token)
      localStorage.setItem('currentUser', JSON.stringify(response.data.user))
      // 返回正确的用户对象，以便组件可以正确访问
      return {
        ...response,
        user: response.data.user,
        token: response.data.token
      }
    }
    return response
  }

  /**
   * 用户注销
   */
  async logout() {
    try {
      await this.post('/auth/logout')
    } catch (error) {
      console.warn('注销请求失败:', error)
    } finally {
      this.clearAuth()
    }
  }

  /**
   * 获取当前用户信息
   */
  async getCurrentUser() {
    const response = await this.get('/auth/me')
    // 后端返回的数据结构是 {success, data: {user}}
    if (response.data) {
      return response.data
    }
    return response
  }

  /**
   * 刷新战斗力
   */
  async refreshBattlePower() {
    const response = await this.post('/auth/refresh-battle-power')
    // 后端返回的数据结构是 {success, message, data: {battlePower}}
    if (response.data) {
      return response.data
    }
    return response
  }

  /**
   * 更新个人资料
   */
  async updateProfile(userData) {
    const response = await this.put('/auth/update-profile', userData)
    // 后端返回的数据结构是 {success, message, data: {user}}
    if (response.data) {
      return response.data
    }
    return response
  }

  /**
   * 获取用户统计数据
   */
  async getUserStats() {
    const response = await this.get('/auth/stats')
    // 后端返回的数据结构是 {success, data}
    if (response.data) {
      return response.data
    }
    return response
  }

  /**
   * 获取用户操作日志
   */
  async getUserLogs() {
    const response = await this.get('/auth/logs')
    // 后端返回的数据结构是 {success, data: {logs}}
    if (response.data) {
      return response.data.logs || []
    }
    return []
  }

  /**
   * 上传用户头像
   */
  async uploadAvatar(formData) {
    // 注意：对于文件上传，我们需要特殊处理请求头
    const config = {
      method: 'POST',
      body: formData
      // 不要设置 Content-Type，让浏览器自动设置 multipart/form-data
    };

    const response = await this.request('/auth/upload-avatar', config);
    // 确保返回正确的数据结构
    return response;
  }

  // ==================== 视频课程API ====================

  /**
   * 获取视频课程列表
   */
  async getVideoCourses(params = {}) {
    const response = await this.get('/video-courses', params)
    // 后端返回的数据结构是 {success, data: {videoCourses, pagination}}
    if (response.data) {
      return {
        ...response,
        courses: response.data.videoCourses || [],
        pagination: response.data.pagination
      }
    }
    return response
  }

  /**
   * 获取视频课程详情
   */
  async getVideoCourse(courseId) {
    const response = await this.get(`/video-courses/${courseId}`)
    // 后端返回的数据结构是 {success, data: {videoCourse}}
    if (response.data) {
      return {
        ...response,
        course: response.data // 注意这里是 videoCourse 而不是 course
      }
    }
    return response
  }

  /**
   * 创建视频课程
   */
  async createVideoCourse(courseData) {
    const response = await this.post('/video-courses', courseData)
    // 后端返回的数据结构是 {success, message, data: {videoCourse}}
    if (response.data) {
      return response.data
    }
    return response
  }

  /**
   * 更新视频课程
   */
  async updateVideoCourse(courseId, courseData) {
    const response = await this.put(`/video-courses/${courseId}`, courseData)
    // 后端返回的数据结构是 {success, message, data: {videoCourse}}
    if (response.data) {
      return response.data
    }
    return response
  }

  /**
   * 删除视频课程
   */
  async deleteVideoCourse(courseId) {
    const response = await this.delete(`/video-courses/${courseId}`)
    // 后端返回的数据结构是 {success, message}
    return response
  }

  /**
   * 为课程添加章节
   */
  async addVideoChapter(courseId, chapterData) {
    const response = await this.post(`/video-courses/${courseId}/chapters`, chapterData)
    // 后端返回的数据结构是 {success, message, data: {videoChapter}}
    if (response.data) {
      return response.data
    }
    return response
  }

  /**
   * 更新章节
   */
  async updateVideoChapter(courseId, chapterId, chapterData) {
    const response = await this.put(`/video-courses/${courseId}/chapters/${chapterId}`, chapterData)
    // 后端返回的数据结构是 {success, message, data: {videoChapter}}
    if (response.data) {
      return response.data
    }
    return response
  }

  /**
   * 删除章节
   */
  async deleteVideoChapter(courseId, chapterId) {
    const response = await this.delete(`/video-courses/${courseId}/chapters/${chapterId}`)
    // 后端返回的数据结构是 {success, message}
    return response
  }

  /**
   * 上传视频文件
   */
  async uploadVideo(formData, onUploadProgress) {
    // 注意：对于文件上传，我们需要特殊处理请求头
    const config = {
      method: 'POST',
      body: formData
      // 不要设置 Content-Type，让浏览器自动设置 multipart/form-data
    };

    // 如果提供了进度回调函数，则添加上传进度监听
    if (onUploadProgress) {
      // 创建一个自定义的 fetch 包装器来处理进度
      return await this.requestWithProgress('/video-courses/upload', config, onUploadProgress);
    }

    const response = await this.request('/video-courses/upload', config);
    // 确保返回正确的数据结构
    return response;
  }

  /**
   * 带进度回调的请求方法
   */
  async requestWithProgress(url, options) {
    const config = {
      headers: {},
      ...options
    };

    // 添加认证token
    if (this.token) {
      config.headers.Authorization = `Bearer ${this.token}`;
    }

    // 删除Content-Type头，让浏览器自动设置
    delete config.headers['Content-Type'];

    try {
      const response = await fetch(`${API_BASE_URL}${url}`, config);
      
      // 检查响应状态
      if (!response.ok) {
        if (response.status === 401) {
          // Token过期，清除本地token
          this.clearAuth();
          throw new Error('认证失败，请重新登录');
        }
        const errorData = await response.json();
        throw new Error(errorData.message || `HTTP ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('API请求失败:', error);
      throw error;
    }
  }

  // ==================== 任务管理API ====================

  /**
   * 获取任务列表
   */
  async getTasks(params = {}) {
    const response = await this.get('/tasks', params)
    // 后端返回的数据结构是 {success, data: {tasks, pagination}}
    if (response.data) {
      return {
        ...response,
        tasks: response.data.tasks || [],
        pagination: response.data.pagination
      }
    }
    return response
  }

  /**
   * 获取任务详情
   */
  async getTask(taskId) {
    const response = await this.get(`/tasks/${taskId}`)
    // 后端返回的数据结构是 {success, data: {task}}
    if (response.data) {
      return {
        ...response,
        task: response.data
      }
    }
    return response
  }

  /**
   * 创建任务
   */
  async createTask(taskData) {
    return this.post('/tasks', taskData)
  }

  /**
   * 更新任务
   */
  async updateTask(taskId, taskData) {
    return this.put(`/tasks/${taskId}`, taskData)
  }

  /**
   * 删除任务
   */
  async deleteTask(taskId) {
    return this.delete(`/tasks/${taskId}`)
  }

  /**
   * 切换任务状态
   */
  async toggleTaskStatus(taskId) {
    return this.put(`/tasks/${taskId}/toggle`)
  }

  /**
   * 更新任务排序
   */
  async reorderTasks(taskIds) {
    console.log('调用 reorderTasks API，taskIds:', taskIds);
    try {
      const result = await this.put('/tasks/reorder', { taskIds });
      console.log('reorderTasks API 调用成功，结果:', result);
      return result;
    } catch (error) {
      console.error('reorderTasks API 调用失败:', error);
      throw error;
    }
  }

  /**
   * 初始化任务排序
   */
  async initializeTaskOrder() {
    return this.post('/tasks/initialize-order')
  }

  // ==================== 笔记课程API ====================

  /**
   * 获取笔记课程列表
   */
  async getCourses(params = {}) {
    const response = await this.get('/courses', params)
    // 后端返回的数据结构是 {success, data: {courses, pagination}}
    if (response.data) {
      return {
        ...response,
        courses: response.data.courses || [],
        pagination: response.data.pagination
      }
    }
    return response
  }

  /**
   * 获取笔记课程详情
   */
  async getCourse(courseId) {
    const response = await this.get(`/courses/${courseId}`)
    // 后端返回的数据结构是 {success, data: {course}}
    if (response.success && response.data) {
      return {
        ...response,
        course: response.data
      }
    }
    return response
  }

  /**
   * 创建笔记课程
   */
  async createCourse(courseData) {
    return this.post('/courses', courseData)
  }

  /**
   * 更新笔记课程
   */
  async updateCourse(courseId, courseData) {
    return this.put(`/courses/${courseId}`, courseData)
  }

  /**
   * 删除笔记课程
   */
  async deleteCourse(courseId) {
    return this.delete(`/courses/${courseId}`)
  }

  /**
   * 为课程添加章节
   */
  async addCourseChapter(courseId, chapterData) {
    return this.post(`/courses/${courseId}/chapters`, chapterData)
  }

  /**
   * 更新课程章节
   */
  async updateCourseChapter(courseId, chapterId, chapterData) {
    return this.put(`/courses/${courseId}/chapters/${chapterId}`, chapterData)
  }

  /**
   * 删除课程章节
   */
  async deleteCourseChapter(courseId, chapterId) {
    return this.delete(`/courses/${courseId}/chapters/${chapterId}`)
  }

  // ==================== 用户管理API ====================

  /**
   * 获取用户列表（仅管理员）
   */
  async getUsers() {
    const response = await this.get('/auth/users')
    // 后端返回的数据结构是 {success, data: {users}}
    if (response.data) {
      return response.data.users || []
    }
    return []
  }

  /**
   * 创建用户（仅管理员）
   */
  async createUser(userData) {
    const response = await this.post('/auth/users', userData)
    // 后端返回的数据结构是 {success, message, data: {user}}
    if (response.data) {
      return response.data
    }
    return response
  }

  /**
   * 更新用户信息（仅管理员）
   */
  async updateUser(userId, userData) {
    const response = await this.put(`/auth/users/${userId}`, userData)
    // 后端返回的数据结构是 {success, message, data: {user}}
    if (response.data) {
      return response.data
    }
    return response
  }

  /**
   * 删除用户（仅管理员）
   */
  async deleteUser(userId) {
    const response = await this.delete(`/auth/users/${userId}`)
    // 后端返回的数据结构是 {success, message}
    return response
  }

  /**
   * 清空所有数据（仅管理员）
   */
  async clearAllData() {
    const response = await this.request('/auth/clear-all-data', {
      method: 'DELETE'
    })
    return response
  }
}

// 创建单例实例
const apiService = new ApiService()

export default apiService